package com.sgb.kjwl.view.ui.fragment.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.sgb.jicai.view.fragment.FactoryCentralizedFragment;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentHomeMaterialBinding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.swgk.core.view.entity.MenuEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.view.event.CategoryEvent;
import com.sgb.kjwl.view.event.ChooseAreaEvent;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.link.event.MaterialEvent;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.ui.activity.ShoppingCar.ShoppingCartActivity;
import com.sgb.kjwl.view.ui.activity.home.HomeCategoryActivity;
import com.sgb.kjwl.view.ui.activity.home.SearchActivity3;
import com.sgb.kjwl.view.ui.activity.material.hall.NewDemandHallActivity;
import com.sgb.kjwl.view.ui.activity.power.PowerListActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.activity.supplier3.SupplierActivity4;
import com.sgb.kjwl.view.ui.adapter.home.GoodsNavigationAdapter;
import com.sgb.kjwl.view.ui.adapter.home.MateriaIndustryAdapter;
import com.sgb.kjwl.view.ui.adapter.home.TabFragmentStateAdapter;
import com.sgb.kjwl.view.ui.fragment.HomeFragment3;
import com.sgb.kjwl.view.ui.fragment.material.MerchantRecommendationFragment;
import com.sgb.kjwl.view.ui.fragment.material.NewDemandHallFragment;
import com.swgk.core.view.weiget.CountMenuView;
import com.sgb.kjwl.view.widget.HomeGoodsSelectionTypePopWindow;
import com.sgb.kjwl.viewmodel.home.MaterialHomeModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.refresh.SuperSwipeRefreshLayout;
import com.swgk.core.util.MLog;
import com.swgk.core.util.ScaleUtils;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.xrecyclerview.AppBarStateChangeListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import static com.swgk.core.event.EventConstant.EVENT_GOODS_HOME_JUMP;
import static com.swgk.core.event.EventConstant.EVENT_MAP_HOME_JUMP;

/**
 * @author Administrator`
 * 首页的商品界面
 * 已弃用 使用MaterialHomeFragment1代替
 */
@Deprecated
public class MaterialHomeFragment extends AppFragment {

    private FragmentHomeMaterialBinding mBinding;
    @Inject
    MaterialHomeModel model;
    public static final String KEY_TYPE = "type";
    private boolean isCreate = false;
    private boolean init = true;
    private boolean isVisible;
    private GoodsNavigationAdapter goodsNavigationAdapter;
    private MateriaIndustryAdapter materiaIndustryAdapter;
    private HomeGoodsSelectionTypePopWindow homeGoodsSelectionTypePopWindow;
    private List<MenuEntity> bundleData = new ArrayList<>();
    private List<MenuEntity> data;
    private List<MenuEntity> dataList = new ArrayList<>();
    private List<MenuEntity> menuList = new ArrayList<>();
    private List<MenuEntity> industryList;
    private HomeFragment3 homeFragment3;
    private TextView textView;
    private boolean isExpand;
    private boolean isLoad;
    String mIndustryId = "";
    String mIndustry = "";

    private final String[] tagName = {"商品", "自营", "集采", "促销", "需求大厅", "供应商"};
    private TabFragmentStateAdapter mTabFragmentStateAdapter;
    List<Fragment> fragmentList = new ArrayList<>();
    private boolean isOnClickAction = false;
    private int industryPosition;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_home_material, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    public static MaterialHomeFragment newInstance(String type) {
        MaterialHomeFragment fragment = new MaterialHomeFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_TYPE, type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;
        if (!isCreate) {
            return;
        }
        if (isVisibleToUser) {
            if (init) {
                init = false;
                initView();
                init();
            }
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        isCreate = true;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        if (init && isVisible) {
            init = false;
            init();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(LoginEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_SHOPPING_LOGIN) {
            SharedPreferenceUtil.getInstance().saveString("EVENT_SHOPPING_TYPE", "");
        }
    }

    private void initView() {
        mBinding.imgShopCar.setOnClickListener(this);
        mBinding.imgBackTop.setOnClickListener(this);
        mBinding.llBtn.setOnClickListener(this);
        mBinding.ivAskPrice.setOnClickListener(this);
        mBinding.swipeRefresh.setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {
            @Override
            public void onRefresh() {
                textView.setText("正在刷新");
                model.getMenuModel("", mIndustryId);
                model.recommendMenu();
                refreshFragment();
            }

            @Override
            public void onPullDistance(int distance) {

            }

            @Override
            public void onPullEnable(boolean enable) {
                textView.setText(enable ? "释放立即刷新" : "下拉刷新");
            }
        });

        mBinding.swipeRefresh.setHeaderView(createHeaderView());

        if (materiaIndustryAdapter == null) {
            materiaIndustryAdapter = new MateriaIndustryAdapter(getActivity(), null);
        }
        LinearLayoutManager rvClassifyBtnM = new LinearLayoutManager(getActivity());
        mBinding.rvClassify.setLayoutManager(rvClassifyBtnM);
        mBinding.rvClassify.setAdapter(materiaIndustryAdapter);
        materiaIndustryAdapter.setItemSelect(true);
        materiaIndustryAdapter.setOnItemClick(new AdapterOnItemClick<MenuEntity>() {
            @Override
            public void onItemClick(MenuEntity menuEntity, int position) {
                mIndustryId = menuEntity.getId();
                mIndustry = menuEntity.getName();
                isOnClickAction = true;
                industryPosition = position;
                model.getMenuModel("", mIndustryId);
                isExpand = true;
                expend();
            }
        });

        goodsNavigationAdapter = new GoodsNavigationAdapter(getContext(), null);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        mBinding.recyclerViewImg.setLayoutManager(linearLayoutManager);
        mBinding.recyclerViewImg.setAdapter(goodsNavigationAdapter);
        goodsNavigationAdapter.setOnItemClick(new AdapterOnItemClick<MenuEntity>() {
            @Override
            public void onItemClick(MenuEntity menuEntity, int position) {
                if ("2".equals(menuEntity.getId())) {
                    homeFragment3.goLogin(getActivity());
                } else if ("26".equals(menuEntity.getId())) {
                    SupplierActivity4.start(getActivity(), true, bundleData);
                } else if ("23".equals(menuEntity.getId())) {
                    NewDemandHallActivity.start(getActivity());
                } else {
                    List<MenuEntity> menuEntities = getMenuEntities(goodsNavigationAdapter.getDatas());
                    menuEntities.remove(5); //需求大厅
                    menuEntities.remove(5); //查找地图
                    if (position == 7) {
                        position = 5;
                    }
//                    GoodsAggregateActivity.start(getActivity(), menuEntities, position, bundleData);
                }
            }
        });

        homeGoodsSelectionTypePopWindow = new HomeGoodsSelectionTypePopWindow(getActivity());
        homeGoodsSelectionTypePopWindow.setDefItem(0);
        mBinding.appBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (state == State.EXPANDED) {
                    //展开状态
                    EventBus.getDefault().postSticky(new MaterialEvent().setMessageTag(EventConstant.EVENT_APPBAR_STATE_EXPANDED));
                    mBinding.swipeRefresh.setEnabled(true);
                } else if (state == State.COLLAPSED) {
                    //折叠状态
                    EventBus.getDefault().postSticky(new MaterialEvent().setMessageTag(EventConstant.EVENT_APPBAR_STATE_COLLAPSED));
                    mBinding.swipeRefresh.setEnabled(false);
                } else {
                    //中间状态
                    mBinding.swipeRefresh.setEnabled(false);
                    EventBus.getDefault().postSticky(new MaterialEvent().setMessageTag(EventConstant.EVENT_APPBAR_STATE_COMMON));
                }
            }
        });
        mBinding.appBarLayout.post(this::initAppbar);
        mBinding.llClassify.setVisibility(View.GONE);
    }

    private void refreshFragment() {
        MaterialEvent materialEvent = new MaterialEvent();
        materialEvent.setMessageTag(EventConstant.EVENT_REFRESH_FRAGMENT);
        EventBus.getDefault().post(materialEvent);
    }

    /***
     * 复制MenuEntity数组
     * @param menuEntities
     * @return
     */
    private List<MenuEntity> getMenuEntities(List<MenuEntity> menuEntities) {
        List<MenuEntity> menuEntityList = new ArrayList<>();
        if (menuEntities != null || menuEntities.size() > 0) {
            for (MenuEntity menuEntity : menuEntities) {
                MenuEntity menuEntity1 = new MenuEntity();
                menuEntity1.setDatas(menuEntity.getDatas());
                menuEntity1.setUrl(menuEntity.getUrl());
                menuEntity1.setSelected(menuEntity.isSelected());
                menuEntity1.setParentId(menuEntity.getParentId());
                menuEntity1.setName(menuEntity.getName());
                menuEntity1.setImageResource(menuEntity.getImageResource());
                menuEntity1.setId(menuEntity.getId());
                menuEntity1.setIconContent(menuEntity.getIconContent());
                menuEntity1.setHostImg(menuEntity.getHostImg());
                menuEntity1.setAppIconUrl(menuEntity.getAppIconUrl());
                menuEntity1.setAppIcon(menuEntity.getAppIcon());
                menuEntityList.add(menuEntity1);
            }
        }
        return menuEntityList;
    }

    public void initAppbar() {
        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) mBinding.appBarLayout.getLayoutParams();
        AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior();
        if (behavior != null) {
            behavior.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
                @Override
                public boolean canDrag(@NonNull AppBarLayout appBarLayout) {
                    return true;
                }
            });
        }
    }


    private View createHeaderView() {
        View headerView = LayoutInflater.from(mBinding.swipeRefresh.getContext())
                .inflate(R.layout.super_swipe_refresh_head, null);
        ProgressBar progressBar = headerView.findViewById(R.id.pb_view);
        textView = headerView.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        progressBar.setVisibility(View.GONE);
        return headerView;
    }


    private void init() {
        model.getMenuModel("", mIndustryId);
        model.recommendMenu();
        homeFragment3 = (HomeFragment3) getParentFragment();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_more:
                EventBus.getDefault().postSticky(CategoryEvent.make(EventConstant.EVENT_CATEGORY_CHOOSE, 0));
                HomeCategoryActivity.start(getActivity());
                break;
            case R.id.ll_see_more:
                if (null == data || data.size() == 0) {
                    return;
                }
                homeGoodsSelectionTypePopWindow.setData(dataList);
                break;
            case R.id.et_view:
                SearchActivity3.start(getActivity(), 0);
                break;
            case R.id.img_back_top:
                scrollToTop();
                break;
            case R.id.img_shop_car:
                if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, "").equals("")) {
                    EventBus.getDefault().postSticky("transport_to_login");
                } else {
                    ShoppingCartActivity.start(getActivity());
                }
                break;
            case R.id.ll_btn:
                if (industryList == null) {
                    model.getIndustryList();
                } else {
                    expend();
                }
                break;
            case R.id.iv_ask_price:
                homeFragment3.goLogin(getContext());
                break;
            default:
                break;
        }
    }

    private void expend() {
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mBinding.llClassify.getLayoutParams();
        if (!isExpand) {
            lp.leftMargin = 0;
            mBinding.ivClassify.setRotation(0);
        } else {
            lp.leftMargin = ScaleUtils.px2dip(getActivity(), -65);
            mBinding.ivClassify.setRotation(180);
        }
        mBinding.llClassify.setLayoutParams(lp);
        isExpand = !isExpand;
    }

    public void scrollToTop() {
        //拿到 appbar 的 behavior,让 appbar 滚动
        ViewGroup.LayoutParams layoutParams = mBinding.appBarLayout.getLayoutParams();
        AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) ((CoordinatorLayout.LayoutParams) layoutParams).getBehavior();
        if (behavior != null) {
            //拿到下方tabs的y坐标，即为我要的偏移量
            float y = mBinding.calendarMenuView.getY();
            //注意传递负值
            behavior.setTopAndBottomOffset((int) -y);
        }
    }

    public List<MenuEntity> getData() {
        return goodsNavigationAdapter.getDatas();
    }

    public void showImageButton(List<MenuEntity> dataList) {
        goodsNavigationAdapter.setDatas(dataList);
    }

    public void showIndustry(List<MenuEntity> datas) {
        this.industryList = datas;
        MenuEntity all = new MenuEntity("", "全部");
        industryList.add(0, all);
        materiaIndustryAdapter.setDefItem(0);
        materiaIndustryAdapter.setDatas(industryList);
        expend();
    }

    public List<MenuEntity> getAllData() {
        return data;
    }

    public void showMenuView(List<MenuEntity> data) {
        menuList.clear();
        if (data != null) {
            for (int i = 0; i < data.size(); i++) {
                MenuEntity entity = new MenuEntity();
                entity.setAppIcon(data.get(i).getAppIcon());
                entity.setAppIconUrl(data.get(i).getAppIconUrl());
                entity.setId(data.get(i).getId());
                entity.setSelected(data.get(i).isSelected());
                entity.setUrl(data.get(i).getUrl());
                if (data.get(i).getName().length() > 6) {
                    String name = data.get(i).getName().substring(0, 5) + "...";
                    entity.setName(name);
                } else {
                    entity.setName(data.get(i).getName());
                }
                menuList.add(entity);
            }
        }
        dataList.clear();
        mBinding.swipeRefresh.setRefreshing(false);
        data.remove(0);
        menuList.remove(0);
        List<MenuEntity> entityList = buildMenuList(menuList);
        bundleData.addAll(data);
        this.data = data;
        dataList.addAll(data);
        mBinding.calendarMenuView.initData(getChildFragmentManager(), menuList, new CountMenuView.OnItemClick() {
            @Override
            public void onItemClick(MenuEntity entity, int position, int num) {
                EventBus.getDefault().postSticky(CategoryEvent.make(EventConstant.EVENT_CATEGORY_CHOOSE, num));
                //GoodsAggregateActivity.start(getActivity(), getData(), 0, bundleData, entity.getId());
            }
        });
        MenuEntity menuEntity = new MenuEntity();
        menuEntity.setName("全部");
        menuEntity.setId("");
        dataList.add(0, menuEntity);
        if (!entityList.contains("全部")) {
            MenuEntity menuEntity1 = new MenuEntity();
            menuEntity1.setName("全部");
            menuEntity1.setId("");
            entityList.add(0, menuEntity1);
        }
        MaterialEvent materialEvent = new MaterialEvent();
        if (isLoad && isOnClickAction) {
            materialEvent.setMessageData(entityList);
            materialEvent.setObject(industryPosition);
            mBinding.viewPager.setCurrentItem(0);
            isOnClickAction = false;
            materialEvent.setMessageTag(EventConstant.EVENT_NEW_TAB_VALUE);
            EventBus.getDefault().post(materialEvent);
        }
        FragmentTransaction fragmentManager = getChildFragmentManager().beginTransaction();
        if (!isLoad) {
            GoodsMainGoodsListFragment mGoods = GoodsMainGoodsListFragment.newInstance(0, dataList, "0", mIndustry, "0", false, false, false);
            mGoods.setParentFragment(this);
            fragmentList.add(mGoods);
            /***
             * 自营商品Fragment
             */
            GoodsMainGoodsListFragment selfEmployedGoods = GoodsMainGoodsListFragment.newInstance(0, dataList, "0", mIndustry, "0", true, false, false);
            selfEmployedGoods.setParentFragment(this);
            fragmentList.add(selfEmployedGoods);

            fragmentList.add(FactoryCentralizedFragment.newInstance(0, "0"));

            GoodsMainGoodsListFragment promotionGoodsFragment = GoodsMainGoodsListFragment.newInstance(0, dataList, "0", mIndustry, "0", false, true, false);
            promotionGoodsFragment.setParentFragment(this);
            fragmentList.add(promotionGoodsFragment);

            fragmentList.add(NewDemandHallFragment.newInstance("", ""));

            fragmentList.add(MerchantRecommendationFragment.newInstance());

            if (mTabFragmentStateAdapter == null) {
                mTabFragmentStateAdapter = new TabFragmentStateAdapter(getActivity(), fragmentList);
            }
            mBinding.viewPager.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
            mBinding.viewPager.setAdapter(mTabFragmentStateAdapter);
            new TabLayoutMediator(mBinding.tabLayout, mBinding.viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
                @Override
                public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                    tab.setText(tagName[position]);
                }
            }).attach();
//            mBinding.viewPager.setOffscreenPageLimit(fragmentList.size());
            isLoad = true;
        }

        fragmentManager.commitAllowingStateLoss();
    }

    /***
     *
     * @param menuList
     */
    private List<MenuEntity> buildMenuList(List<MenuEntity> menuList) {
        List<MenuEntity> menuEntities = new ArrayList<>();
        if (menuList != null && menuList.size() > 0) {
            for (MenuEntity menuEntity : menuList) {
                MenuEntity entity = new MenuEntity();
                entity.setName(menuEntity.getName());
                entity.setId(menuEntity.getId());
                entity.setDatas(menuEntity.getDatas());
                menuEntities.add(entity);
            }
        }
        return menuEntities;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MenuEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_MENU_POWER) {
            MLog.d("api", event.getNo());
            PowerListActivity.start(getActivity(), event.getNo(), event.getChildNo());
        } else if (event.getMessageTag() == EVENT_GOODS_HOME_JUMP) {
        } else if (event.getMessageTag() == EVENT_MAP_HOME_JUMP) {
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MaterialEvent event) {

        if (event.getMessageTag() == EventConstant.EVENT_LOGISTICS_WINDOW_TOP) {

            mBinding.appBarLayout.setExpanded(false);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(ChooseAreaEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CHOOSE_AERA) {
            if (mBinding == null || mBinding.swipeRefresh == null || model == null) {
                return;
            }
            mBinding.swipeRefresh.setRefreshing(false);
            textView.setText("正在刷新");
            model.getMenuModel("", mIndustryId);
            model.recommendMenu();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void jumpLogin() {
        VerificationCodeLoginActivity.start(getActivity());
    }

    /**
     * 一键登录成功
     *
     * @param loginEntity
     * @param phoneNumber
     */
    public void loginSucceed(LoginEntity loginEntity, String phoneNumber) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageData(phoneNumber);
        loginEvent.setMessageTag(EventConstant.EVENT_LOGIN);
        loginEvent.setObject(loginEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void getUserMsgSucceed(UserMsgEntity userMsgEntity) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageTag(EventConstant.EVENT_USER_MSG);
        loginEvent.setMessageData(userMsgEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }


    public void startForResemble(String one, String two, String three, int position) {
        //GoodsAggregateActivity.start(getActivity(), goodsNavigationAdapter.getDatas(), position, bundleData, one, two, three);
    }

    public void startForMore() {
        //GoodsAggregateActivity.start(getActivity(), goodsNavigationAdapter.getDatas(), 0, bundleData);
    }

    public void startForProvider() {
        //GoodsAggregateActivity.start(getActivity(), goodsNavigationAdapter.getDatas(), 3, bundleData);
    }
}